package com.example.myapplication.activity.mine;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myapplication.R;
import com.example.myapplication.activity.MainActivity;
import com.example.myapplication.bean.LoginBean;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Author: Ng
 * @Date: 2024/4/7
 * @Versopn: 1.0.0
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText login_name;
    private EditText login_password;
    private Button   login_button;
    private Button   register_button;

    private String token;
    private int code;
    private Intent intent = null;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg == obtainMessage()) {
                Toast.makeText(getApplicationContext(), "登录成功！", Toast.LENGTH_LONG).show();
            }
        }
    };

    @Override
    protected void onCreate(@NonNull Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
        // 初始化控件
        initView();
    }

    private void initView() {
        login_name = (EditText) findViewById(R.id.login_name);
        login_password = (EditText) findViewById(R.id.login_password);
        login_button = (Button) findViewById(R.id.login_button);
        register_button = (Button) findViewById(R.id.register_button);
        login_button.setOnClickListener(this);
        register_button.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.login_button:
                login();
                break;
            case R.id.register_button:
                intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void login() {
        final String username = login_name.getText().toString().trim();
        final String password = login_password.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {
            Toast.makeText(this, "请输入用户名！", Toast.LENGTH_SHORT).show();
            return;
        } else if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请输入密码！", Toast.LENGTH_SHORT).show();
            return;
        } else if (true) {
            OkHttpClient client = new OkHttpClient();
            // 提交的参数
            final JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("username", username);
                jsonObject.put("password", password);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
            final RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url("http://xxxx/login")
                    .build();
            okhttp3.Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.i("【请求状态】", "请求失败！");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        Log.i("【响应状态】", "响应成功！");
                        final String loginBody = response.body().string();
                        Gson gson = new Gson();
                        LoginBean loginBean = gson.fromJson(loginBody, LoginBean.class);
                        String loginResultCode = loginBean.getCode();
                        Log.i("【返回状态码】", loginResultCode);
                        // 响应成功 判断状态码
                        if (loginResultCode.equals("200")) {
                            Log.i("【登录状态】", "登录成功！");
                            // 获取 token
                            token = loginBean.getToken();
                            // 把 token 存储在本地
                            SharedPreferences.Editor editor = getSharedPreferences("token", MODE_PRIVATE).edit();
                            editor.putString("token", token);
                            editor.putString("username", username);
                            editor.putString("password", password);
                            editor.apply();
                            // 登录成功 跳转到主界面
                            Message message = handler.obtainMessage();
                            message.obj = token;
                            handler.sendMessage(message);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), loginBody, Toast.LENGTH_LONG).show();
                                }
                            });
                            startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            finish();
                        } else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(getApplicationContext(), "登录失败！", Toast.LENGTH_LONG).show();
                                }
                            });
                        }

                    }
                }
            });
        }
    }
}
